const { DataTypes, Model } = require('sequelize');
const { sequelize } = require('../config/database');

class Service extends Model {
  // 计算服务价格
  calculatePrice(options = {}) {
    const {
      duration = this.characteristics?.duration?.default || 1,
      petCount = 1,
      isEmergency = false,
      isWeekend = false,
      isHoliday = false,
      caregiverRate = null
    } = options;
    
    const pricing = this.pricing || {};
    let basePrice = caregiverRate || pricing.basePrice || 0;
    
    // 根据定价单位计算基础费用
    let totalPrice = 0;
    switch (pricing.priceUnit) {
      case 'per_hour':
        totalPrice = basePrice * duration;
        break;
      case 'per_day':
        totalPrice = basePrice * Math.ceil(duration / 24);
        break;
      case 'per_service':
        totalPrice = basePrice;
        break;
      case 'per_pet':
        totalPrice = basePrice * petCount;
        break;
      default:
        totalPrice = basePrice * duration;
    }
    
    // 额外宠物费用
    if (petCount > 1) {
      const additionalPets = petCount - 1;
      totalPrice += totalPrice * (pricing.additionalPetMultiplier || 0.5) * additionalPets;
    }
    
    // 应用倍数
    if (isEmergency) {
      totalPrice *= (pricing.emergencyMultiplier || 1.5);
    }
    if (isWeekend) {
      totalPrice *= (pricing.weekendMultiplier || 1.2);
    }
    if (isHoliday) {
      totalPrice *= (pricing.holidayMultiplier || 1.5);
    }
    
    return Math.round(totalPrice * 100) / 100;
  }

  // 更新统计信息
  async updateStats(orderData) {
    const stats = this.stats || {
      totalOrders: 0,
      completedOrders: 0,
      averageRating: 0,
      ratingCount: 0,
      averageDuration: 0,
      popularityScore: 0
    };
    
    stats.totalOrders += 1;
    
    if (orderData.completed) {
      stats.completedOrders += 1;
    }
    
    if (orderData.rating) {
      const currentTotal = stats.averageRating * stats.ratingCount;
      stats.ratingCount += 1;
      stats.averageRating = (currentTotal + orderData.rating) / stats.ratingCount;
    }
    
    if (orderData.duration) {
      const currentTotal = stats.averageDuration * (stats.totalOrders - 1);
      stats.averageDuration = (currentTotal + orderData.duration) / stats.totalOrders;
    }
    
    this.stats = stats;
    await this.updatePopularityScore();
    return this.save({ validate: false });
  }

  // 更新受欢迎程度分数
  async updatePopularityScore() {
    const stats = this.stats || {};
    const completionRate = stats.totalOrders > 0 ? (stats.completedOrders / stats.totalOrders) * 100 : 0;
    const rating = stats.averageRating || 0;
    const orderVolume = Math.min((stats.totalOrders || 0) / 100, 1) * 100;
    
    stats.popularityScore = Math.round(
      (completionRate * 0.3) + 
      (rating * 20 * 0.4) + 
      (orderVolume * 0.3)
    );
    
    this.stats = stats;
    return stats.popularityScore;
  }

  // 虚拟字段: 完成率
  get completionRate() {
    const stats = this.stats || { totalOrders: 0, completedOrders: 0 };
    if (stats.totalOrders === 0) return 0;
    return (stats.completedOrders / stats.totalOrders) * 100;
  }

  // 虚拟字段: 主要图片
  get primaryImage() {
    const images = this.images || [];
    const primary = images.find(img => img.isPrimary);
    return primary ? primary.url : (images.length > 0 ? images[0].url : null);
  }

  // 虚拟字段: 是否受欢迎
  get isPopular() {
    const stats = this.stats || {};
    return (stats.popularityScore || 0) > 70 && (stats.averageRating || 0) >= 4.0;
  }
}

Service.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  // 基本信息
  name: {
    type: DataTypes.STRING(100),
    allowNull: false
  },
  slug: {
    type: DataTypes.STRING(120),
    unique: true,
    allowNull: false
  },
  category: {
    type: DataTypes.ENUM('basic_care', 'medical_care', 'grooming', 'training', 'entertainment', 'emergency', 'special'),
    allowNull: false
  },
  
  // 描述信息 (JSON)
  description: {
    type: DataTypes.JSON,
    allowNull: false,
    defaultValue: {
      short: '',
      detailed: ''
    }
  },
  
  // 服务图标和图片
  icon: {
    type: DataTypes.STRING(500),
    allowNull: false
  },
  images: {
    type: DataTypes.JSON,
    defaultValue: []
  },
  
  // 适用宠物类型 (JSON)
  applicablePetTypes: {
    type: DataTypes.JSON,
    defaultValue: []
  },
  
  // 服务特征 (JSON)
  characteristics: {
    type: DataTypes.JSON,
    defaultValue: {}
  },
  
  // 所需技能和认证 (JSON)
  requirements: {
    type: DataTypes.JSON,
    defaultValue: {
      skills: [],
      certifications: [],
      experienceLevel: 'beginner',
      minimumRating: 0
    }
  },
  
  // 定价信息 (JSON)
  pricing: {
    type: DataTypes.JSON,
    allowNull: false,
    defaultValue: {
      basePrice: 0,
      priceUnit: 'per_hour',
      additionalPetMultiplier: 0.5,
      emergencyMultiplier: 1.5,
      weekendMultiplier: 1.2,
      holidayMultiplier: 1.5
    }
  },
  
  // 服务流程 (JSON)
  workflow: {
    type: DataTypes.JSON,
    defaultValue: {
      steps: []
    }
  },
  
  // 安全和注意事项 (JSON)
  safety: {
    type: DataTypes.JSON,
    defaultValue: {
      precautions: [],
      contraindications: []
    }
  },
  
  // 质量标准 (JSON)
  qualityStandards: {
    type: DataTypes.JSON,
    defaultValue: {}
  },
  
  // 可用性设置 (JSON)
  availability: {
    type: DataTypes.JSON,
    defaultValue: {
      timeSlots: [],
      advanceBookingRequired: 2,
      maxAdvanceBooking: 720
    }
  },
  
  // 统计信息 (JSON)
  stats: {
    type: DataTypes.JSON,
    defaultValue: {
      totalOrders: 0,
      completedOrders: 0,
      averageRating: 0,
      ratingCount: 0,
      averageDuration: 0,
      popularityScore: 0
    }
  },
  
  // 状态
  status: {
    type: DataTypes.ENUM('active', 'inactive', 'deprecated', 'coming_soon'),
    defaultValue: 'active'
  },
  
  // 标签和搜索 (JSON)
  tags: {
    type: DataTypes.JSON,
    defaultValue: []
  },
  searchKeywords: {
    type: DataTypes.JSON,
    defaultValue: []
  },
  
  // 版本控制
  version: {
    type: DataTypes.STRING(20),
    defaultValue: '1.0.0'
  },
  changelog: {
    type: DataTypes.JSON,
    defaultValue: []
  }
}, {
  sequelize,
  modelName: 'Service',
  tableName: 'services',
  timestamps: true,
  indexes: [
    { fields: ['slug'] },
    { fields: ['category'] },
    { fields: ['status'] }
  ],
  hooks: {
    beforeSave: async (service) => {
      // 生成 slug
      if (service.changed('name') && !service.slug) {
        service.slug = service.name
          .toLowerCase()
          .replace(/[^a-z0-9\s-]/g, '')
          .replace(/\s+/g, '-')
          .replace(/-+/g, '-')
          .trim();
      }
    }
  }
});

module.exports = Service;
